package com.ossjk.qlh.minapp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.util.JwtTokenUtil;
import com.ossjk.core.vo.RequestBean;
import com.ossjk.core.vo.ResponseBean;
import com.ossjk.qlh.minapp.entity.Enterprise;
import com.ossjk.qlh.minapp.entity.Member;
import com.ossjk.qlh.minapp.entity.Orders;
import com.ossjk.qlh.minapp.service.IEnterpriseService;
import com.ossjk.qlh.minapp.service.IMemberService;
import com.ossjk.qlh.minapp.service.IOrdersService;
import com.ossjk.qlh.minapp.vo.MemberVo;
import com.ossjk.qlh.minapp.vo.MembermsgVo;
import com.ossjk.qlh.minapp.vo.OrderSumVo;
import com.ossjk.qlh.minapp.vo.OrdersMenuVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 我的
 *
 * @author parker
 * @since 2020-08-12
 */
@Api(tags = "我的")
@RestController
@RequestMapping("/api/me")
public class MyApiController extends BaseController {

    @Autowired
    private IEnterpriseService iEnterpriseService;
    @Autowired
    private IMemberService iMemberService;
    @Autowired
    private IOrdersService iOrdersService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    //我的模块 - 项目需要整理：
    //0.0.1 个人信息-   头像、昵称、手机号码、工号 、用户权限 （团长）、用户企业 id    【token里面拿】


    @ApiOperation(value = "修改个人信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "昵称", dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String")
    })
    @PostMapping(value = "/editme")
    public ResponseBean editme(@RequestBody RequestBean<Member> requestBean) {
        String name = (String) requestBean.getParam().get("name");
        String phone = (String) requestBean.getParam().get("phone");
        //token 未封装，信息情况下
        //获取参数
        String userId = jwtTokenUtil.getUserId(jwtTokenUtil.getToken(getRequest()));
        Member byId = iMemberService.getById(userId);
        if (!CommonUtil.isBlank(name)) {
            byId.setName(name);
        }
        if (!CommonUtil.isBlank(phone)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.notIn(phone);
            List<Member> list = iMemberService.list(wrapper);
            for (Member member : list) {
                if (phone.equals(member.getPhone())) {
                    return responseFail("该电话号码已被注册使用！");
                }
            }
            byId.setPhone(phone);
        }
        if (iMemberService.updateById(byId)) {
            return responseSuccess("修改成功！");
        } else {
            return responseFail("修改失败！");
        }
    }

    /**
     * 通过手机号，获取该用户的信息。（没有封装token暂用）
     *
     * @param requestBean
     * @return
     */
    @ApiOperation(value = "个人信息")
    @PostMapping(value = "/getme")
    public ResponseBean getMe(@RequestBody RequestBean<Member> requestBean) {
        //token 未封装，信息情况下
        //获取参数
        String userId = jwtTokenUtil.getUserId(jwtTokenUtil.getToken(getRequest()));
        QueryWrapper<MembermsgVo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("m.id", userId);
        return responseSuccess(iMemberService.getMeMsg(queryWrapper));

    }

    //1.0我的订单

    /**
     * 1.0.1 未接订单（默认显示）
     * 1.0.1.1 取消订单 （未接单可以取消）
     * 1.0.2 已接订单
     * 1.0.3 已配送
     * 1.0.4 全部
     * //1.0.1.4 取消订单 （未接单可以取消） //
     */
    /**
     * 需求信息： 订单id 【orders.code】、 下单时间 【orders.crtm】、接单时间【orders.jdtm】、配送方式【orders.sendway】、
     * 配送时间【orders.sendtm】、
     * 套餐图【setmeal.pic】、菜品表达式:【orderitm.fnames】、小吃【orderitm.otrs】、订单状态【orders.state】
     * <p>
     * 需要的表： orders 、 orderitm,setmeal
     *
     * @param requestBean
     * @return
     */
    @ApiOperation(value = "我的订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mid", value = "成员id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "订单状态", dataType = "String")
    })
    @PostMapping(value = "/myorders")
    public ResponseBean myOrders(@RequestBody RequestBean<Orders> requestBean) {
        String mid = (String) requestBean.getParam().get("mid");
        Integer state = (Integer) requestBean.getParam().get("state");

        if (CommonUtil.isBlank(mid)) {
            return responseFail("用户id不能为空！");
        }

        //数据总容器
        List list = new ArrayList();

        QueryWrapper<Orders> wrapper = new QueryWrapper();
        wrapper.eq("mid", mid);


        if (!CommonUtil.isBlank(state)) {
            wrapper.eq("state", state);
        }

        List<Orders> orders = iOrdersService.list(wrapper);

        QueryWrapper<OrdersMenuVo> wrapper1 = new QueryWrapper();
        wrapper1.eq("o.mid", mid);

        wrapper.eq("state", state);

        List<OrdersMenuVo> ordersMenuVos1 = iOrdersService.queryOrderls(wrapper1);

        for (Orders orders1 : orders) { //订单信息层
            //订单对象容器  订单信息/订单菜单
            Map map = new HashMap();
            List list1 = new ArrayList();
            for (OrdersMenuVo ordersMenuVo : ordersMenuVos1) {//订单菜单层
                if (CommonUtil.isEquals(orders1.getCode(), ordersMenuVo.getCode())) {//订单号相同的
                    list1.add(ordersMenuVo);
                }
            }
            // 订单信息/订单菜单
            map.put("ordermsg", orders1);
            map.put("ordermenu", list1);
            //[{"ordermsg":订单信息,"ordermenu":订单菜单},{"ordermsg":订单信息,"ordermenu":订单菜单}]
            list.add(map);
        }

        return responseSuccess(list);
    }


    @ApiOperation(value = "取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "订单状态", paramType = "query", dataType = "String")
    })
    @PostMapping(value = "/ordercancel")
    public ResponseBean orderCancel(@RequestBody RequestBean<Orders> requestBean) {
        String id = (String) requestBean.getParam().get("id");
        Integer state = (Integer) requestBean.getParam().get("state");
        if (CommonUtil.isBlank(id)) {
            return responseFail("订单id能为空");
        }
        if (CommonUtil.isBlank(state)) {
            return responseFail("订单状态能为空");
        } else if (state != 1) {
            return responseFail("当前订单状态,无法取消订单");
        }

        if (iOrdersService.removeById(id)) {
            return responseSuccess("已取消");
        } else {
            return responseFail("取消失败!后台异常");
        }
    }

    //2.0 收货地址   --  接收收货地址   （仅限团长，才能显示此操作栏）
    @ApiOperation(value = "收货地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "企业id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "mid", value = "成员id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "address", value = "修改地址", paramType = "query", dataType = "String")
    })
    @PostMapping(value = "/udaddress")
    public ResponseBean updateAddress(@RequestBody RequestBean<Enterprise> requestBean) {
        //用户权限校验
        String mid = (String) requestBean.getParam().get("mid");
        Member byId1 = iMemberService.getById(mid);
        if (!(byId1.getState() == 4)) {
            return responseFail("无权限操作!");
        }

        //获取参数 企业id、修改地址
        String id = (String) requestBean.getParam().get("id");
        String address = (String) requestBean.getParam().get("address");

        //查询对应的企业
        Enterprise byId = iEnterpriseService.getById(id);
        if (CommonUtil.isBlank(byId)) {
            return responseFail("无法找到用户所属企业");
        }
        byId.setAddress(address);

        UpdateWrapper wrapper = new UpdateWrapper();

        wrapper.eq("id", id);

        if (iEnterpriseService.update(byId, wrapper)) {
            return responseSuccess("地址修改成功！");
        } else {
            return responseFail("更新失败，数据异常!");
        }

    }

    //3.0 成员管理 （仅限团长）

    /**
     * 3.0.1 成员列表（默认显示）
     * 3.0.2 成员修改
     * 3.0.3 删除
     * 3.0.4 添加成员
     */
    @ApiOperation(value = "成员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eid", value = "企业id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "rname", value = "成员姓名", dataType = "String")
    })
    @PostMapping(value = "/getmemberlist")
    public ResponseBean getMemberlist(@RequestBody RequestBean<Member> requestBean) {
        //获取参数
        String userId = jwtTokenUtil.getUserId(jwtTokenUtil.getToken(getRequest()));
        //用户权限校验
        Member byId = iMemberService.getById(userId);
        if (!(byId.getState() == 4)) {
            return responseFail("无权限操作!");
        }

        //获取参数 企业id、 根据名称 模糊查询
        String eid = (String) requestBean.getParam().get("eid");
        String rname = (String) requestBean.getParam().get("rname");

        if (CommonUtil.isBlank(eid)) {
            return responseFail("企业id不能为空");
        }

        QueryWrapper wrapper = new QueryWrapper();

        wrapper.eq("eid", eid);
        if (!CommonUtil.isBlank(rname)) {
            wrapper.like("rname", rname);
        }


        return responseSuccess(iMemberService.list(wrapper));
    }


    @ApiOperation(value = "修改成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "成员id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "mnum", value = "工号", dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "电话", dataType = "String"),
            @ApiImplicitParam(name = "rname", value = "成员姓名", dataType = "String")
    })
    @PostMapping(value = "/updatemember")
    public ResponseBean updateMember(@RequestBody RequestBean<Member> requestBean) {
        //获取参数 id (必填)， name ，mnum ，phone
        String id = (String) requestBean.getParam().get("id");
        String rname = (String) requestBean.getParam().get("rname");
        String mnum = (String) requestBean.getParam().get("mnum");
        String phone = (String) requestBean.getParam().get("phone");

        Member byId = iMemberService.getById(id);

        if (CommonUtil.isBlank(byId)) {
            return responseFail("没有该成员！");
        }

        if (!CommonUtil.isBlank(rname)) {
            byId.setName(rname);
        }

        if (!CommonUtil.isBlank(mnum)) {
            byId.setMnum(mnum);
        }

        if (!CommonUtil.isBlank(phone)) {
            byId.setPhone(phone);
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.ne("phone", phone);
        List<Member> list = iMemberService.list(wrapper);
        for (Member member : list) {
            if (CommonUtil.isEquals(member.getPhone(), phone)) {
                return responseFail("手机号重复！");
            }
        }
        if (iMemberService.updateById(byId)) {
            return responseSuccess("修改成功！");
        } else {
            return responseFail("修改失败！");
        }

    }


    @ApiOperation(value = "删除成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "成员id", paramType = "query", dataType = "String")
    })
    @PostMapping(value = "/deletemember")
    public ResponseBean deleteMember(@RequestBody RequestBean<Member> requestBean) {

        //获取参数 id (必填)
        String id = (String) requestBean.getParam().get("id");

        if (CommonUtil.isBlank(id)) {
            return responseFail("没有该成员！");
        }

        if (iMemberService.removeById(id)) {
            return responseSuccess("删除成功！");
        } else {
            return responseFail("删除失败！");
        }
    }


    @ApiOperation(value = "新增成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mnum", value = "工号", dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "电话", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "rname", value = "成员姓名", paramType = "query", dataType = "String")
    })
    @PostMapping(value = "/addmember")
    public ResponseBean addMember(@RequestBody RequestBean<Member> requestBean) {

        //用户参数
        String rname = (String) requestBean.getParam().get("rname");

        String phone = (String) requestBean.getParam().get("phone");
        String mnum = (String) requestBean.getParam().get("mnum");

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        Member byId1 = iMemberService.getOne(wrapper);

        //验证用户 和 手机
        if (CommonUtil.isBlank(byId1)) {
            return responseFail("不存在该用户，请先注册");
        }

        if (byId1.getState() != 1) {
            return responseFail("成员已存在，无法新增！");
        }

        if (CommonUtil.isBlank(rname)) {
            return responseFail("成员姓名不能为空！");
        }

        //员工号（可选）
        if (!CommonUtil.isBlank(mnum)) {
            byId1.setMnum(mnum);
        }
        byId1.setRname(rname);

        //新增时，状态为待确认
        byId1.setState(2);

        if (iMemberService.updateById(byId1)) {
            return responseSuccess("新增成功！");
        } else {
            return responseFail("新增失败！");
        }
    }

    //4.0 账单汇总 --  (仅限团长)
    //组成成分: 订单日期、时段、套餐类型、分数合计、时段总金额
    //结论：日期 上午/下午  套餐名 各个套餐数  合计份数 合计金额
    //2020-08-11
    //午餐段：A餐x25 、 B餐x27，合计:52份,600元
    //晚餐段：A餐x25 、 B餐x27，合计:52份,600元
    //格式：[
    //{
    //"times": "2020-08-20",
    //"lun":["午餐时段",[{"title":"xxxx","count":4},{"title":"xxxx","count":4}],4,0],
    //"din":["晚餐时段",[{"title":"xxxx","count":4}],4,0]
    //},
    //
    //{下一天的数据}
    //，
    //{下一天的数据}
    //。。。。
    //]
    @ApiOperation(value = "账单汇总")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eid", value = "成员id", paramType = "query", dataType = "String"),
    })
    @PostMapping(value = "/orderalls")
    public ResponseBean orderAlls(@RequestBody RequestBean<OrderSumVo> requestBean) {

        //获取参数 id (必填)
        String eid = (String) requestBean.getParam().get("eid");

        Member byId = iMemberService.getById(eid);

        if (!(byId.getState() == 4)) {
            return responseFail("无操作权限！");
        }

        //所有日期集合
        Set<String> setdate = new HashSet();

        //午餐
        QueryWrapper<OrderSumVo> queryWrapper = new QueryWrapper<OrderSumVo>();
        queryWrapper.eq("o.eid", byId.getEid());
        queryWrapper.eq("o.type", 1);
        List<OrderSumVo> orderSumVos = iOrdersService.orderAllList(queryWrapper);
        //晚餐
        QueryWrapper<OrderSumVo> queryWrapper1 = new QueryWrapper<OrderSumVo>();
        queryWrapper1.eq("o.eid", byId.getEid());
        queryWrapper1.eq("o.type", 2);
        List<OrderSumVo> orderSumVos1 = iOrdersService.orderAllList(queryWrapper1);

        for (OrderSumVo orderSumVo : orderSumVos) {
            if (!CommonUtil.isBlank(orderSumVo.getCrtm())) {
                setdate.add(new SimpleDateFormat("YYYY-MM-dd").format(orderSumVo.getCrtm()));
            }
        }

        for (OrderSumVo orderSumVo : orderSumVos1) {
            if (!CommonUtil.isBlank(orderSumVo.getCrtm())) {
                setdate.add(new SimpleDateFormat("YYYY-MM-dd").format(orderSumVo.getCrtm()));
            }
        }

        //封装订单汇总信息，得到  [{第一天}，{第二天}]
        List list = new ArrayList();

        for (String o : setdate) { //每日循环得到 一个 {日期1：[obj1,obj2]}
            //每日订单信息（包括午餐/晚餐）
            //每日套餐容器
            Map map = new HashMap();


            List lunval = new ArrayList();
            //晚餐值
            List dinval = new ArrayList();

            //套餐数据
            List lunarry = new ArrayList();
            List dinarry = new ArrayList();

            //套餐总数
            int amountw = 0;
            //时间段总金额
            BigDecimal bigDecimal = new BigDecimal(0);

            //获取 本次循环日期 的 午餐信息 [{"title":"xxxx","count":4}]
            for (OrderSumVo orderSumVoa : orderSumVos) {
                //使用最外出循环的 日期，通过 外层 = 内层 排除其他无关，本循环所需的数据
                if (CommonUtil.isEquals(o, new SimpleDateFormat("YYYY-MM-dd").format(orderSumVoa.getCrtm()))) {
                    Map tcmap = new HashMap();
                    //套餐  名字/数目
                    tcmap.put("title", orderSumVoa.getTitle());
                    tcmap.put("count", orderSumVoa.getAmount());
                    lunarry.add(tcmap);
                    //午餐套餐总数
                    amountw += orderSumVoa.getAmount();
                    //午餐总金额
                    bigDecimal = bigDecimal.add(orderSumVoa.getCostmeal());
                }
            }
//["午餐时段",[{"title":"xxxx","count":4}],4,0]
            //当有套餐时，才新增进去
            if (amountw > 0) {
                //时段
                lunval.add("午餐时段");
                //套餐数据
                lunval.add(lunarry);
                //套餐总数
                lunval.add(amountw);
                //金额
                lunval.add(bigDecimal);
            }

            //套餐总数
            int amountw2 = 0;

            //时间段总金额
            BigDecimal bigDecimal2 = new BigDecimal(0);

            //获取 本次循环日期 的 晚餐信息
            for (OrderSumVo orderSumVob : orderSumVos1) {
                //使用最外出循环的 日期，通过 外层 = 内层 排除其他无关，本循环所需的数据
                if (CommonUtil.isEquals(o, new SimpleDateFormat("YYYY-MM-dd").format(orderSumVob.getCrtm()))) {
                    Map tcmap = new HashMap();
                    //套餐  名字/数目
                    tcmap.put("title", orderSumVob.getTitle());
                    tcmap.put("count", orderSumVob.getAmount());
                    dinarry.add(tcmap);
                    //午餐套餐总数
                    amountw2 += orderSumVob.getAmount();
                    //午餐总金额
                    bigDecimal2 = bigDecimal2.add(orderSumVob.getCostmeal());

                }
            }

            if (amountw2 > 0) {
                //时段
                dinval.add("晚餐时段");
                //套餐数据
                dinval.add(dinarry);
                //套餐总数
                dinval.add(amountw2);
                //金额
                dinval.add(bigDecimal2);
            }

            //存储当天日期
            map.put("times", o);

            //添加数据到集合中
            if (lunval.size() > 0) {
                map.put("lun", lunval);
            }
            if (dinval.size() > 0) {
                map.put("din", dinval);
            }
//----------------------------------------------
            //封装到总容器
            list.add(map);
        }
        System.out.println(list.toString() + "数据");
        return responseSuccess(list);
    }


}
